package org.magicbox.qjunTPO.controller;

import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.User;
import org.magicbox.qjunTPO.service.UploadService;
import org.magicbox.qjunTPO.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/upload")
public class UploadFile {
    @Autowired
    UploadService uploadService ;
    @Autowired
    UserService userService;

    @ResponseBody
    @RequestMapping(value = "/toux",method = RequestMethod.POST)
    public Result uploadToux(@RequestParam("file") MultipartFile multipartFile){

        //判断文件是否为空
        if(multipartFile.isEmpty()) return Result.fail("文件为空",false);

        //获取文件类型
        String contentType = multipartFile.getContentType();

        //文件仅支持jpg png gif jpeg
        if(!contentType.matches("\\S*\\/(jpg|png|gif|jpeg)"))
            return Result.fail("文件类型不合法");

        //头像文件的文件名
        String dir = "toux";

        //存储文件 当文件不规范的时候会失败，将其处理

        //存储文件 且 返回文件存储 的相对路径
        String res_dir = uploadService.uploadImg(multipartFile, dir);
        //获取当前用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid = new Integer(authentication.getName());
        //构建用户对象
        User user = new User();
        user.setId(uid);
        user.setToux(res_dir);

        //修改数据库用户头像路径
        userService.updateById(user);
        System.out.println(res_dir);
        return Result.success("修改头像成功！");
    }
}
